import PageContainer from '@/components/PageContainer';
import { useWalletStore } from '@/hooks';
import useEvent from '@/hooks/useEvent';
import { createDeviceEmergencyContact, fetchDeviceEmergencyContacts, removeDeviceEmergencyContact } from '@/services/emergencyContact';
import { GStyleSheet } from '@/utils/DarkMode';
import { Image, Text, View } from '@tarojs/components';
import Taro, { useRouter } from '@tarojs/taro';
import I18n from 'i18n-js';
import React, { useCallback, useEffect, useState } from 'react';
import AddContact from './add';
import infoIcon from './images/info.png';
import ContactList from './list';

const dstyles = GStyleSheet.create({
  container: {
    height: '100%',
    backgroundColor: '#fff',
    paddingTop: 16,
  },
  tips: {
    margin: '0 40rpx 20rpx',
    display: 'flex',
    alignItems: 'flex-start',
  },
  tipsIcon: {
    width: 16,
    height: 16,
    marginRight: 7,
  },
  tipsText: {
    flex: 1,
  }
});

type Params = {
  mac: string;
  productKey: string;
}

const EmergencyContact = React.memo(() => {
  const styles = dstyles.useDynamicStyle();
  const router = useRouter<Params>();
  const [list, setList] = useState<GetResponseData<typeof fetchDeviceEmergencyContacts>>([]);
  const walletStore = useWalletStore();

  const { mac, productKey } = router.params || {};

  const fetchList = useEvent((showLoading = false) => {
    showLoading && Taro.showLoading();
    return fetchDeviceEmergencyContacts(mac, productKey).then((res) => {
      if (res.success && res.data) {
        setList(res.data);
      }
      return res;
    }).finally(() => {
      showLoading && Taro.hideLoading();
    })
  })

  useEffect(() => {
    fetchList(true);
  }, [fetchList]);

  const handleRemove = useCallback((id: number) => {
    Taro.showLoading();
    removeDeviceEmergencyContact(id)
      .then((res) => {
        if (res.success) {
          return fetchList();
        }
        return res;
      })
      .finally(() => Taro.hideLoading());
  }, [fetchList]);

  const handleAdd = useEvent((nickname: string, mobile: string) => {
    if (list.find(item => mobile === item.mobile)) {
      Taro.showToast({
        icon: 'error',
        title: '重复号码'
      });
      return Promise.resolve({ success: false });
    }

    Taro.showLoading();
    return createDeviceEmergencyContact({
      mac,
      productKey,
      nickname,
      mobile,
    })
      .then((res) => {
        if (res.success) {
          return fetchList()
        }
        return res;
      })
      .finally(() => Taro.hideLoading());
  });

  return (
    <PageContainer title={I18n.t('EMERGENCY_CONTACT')}>
      <View style={styles.container}>
        {walletStore.balance <= 0 && (
          <View style={styles.tips}>
            <Image src={infoIcon} style={styles.tipsIcon} />
            <Text style={styles.tipsText}>{I18n.t('BALANCE_NOT_ENOUGH_TIPS')}</Text>
          </View>
        )}
        {list.length < 3 && (
          <AddContact
            onAdd={handleAdd}
          />
        )}
        <ContactList
          data={list}
          onRemove={handleRemove}
        />
      </View>
    </PageContainer>
  );
});

export default EmergencyContact;
